/**
 * datagrid based on dataTable
 *
 * Dependencies:
 *     dataTable
 *
 */
window.dataTableO='';
(function ($) {
    var tableContainer; // actual table container object
    var tableWrapper; // actual table wrapper jquery object
    var currentDT;//当前DT Object(小曼加的个属性)
    var disabledFalse=0;
    var backfill = {
        onSelect: function (target,node) {
            var boo = true;
            for(var i = 0; i < $.data(target, "datagrid").options.backfillData.length; i++){
                if($.data(target, "datagrid").options.backfillData[i].mid == node.mid){
                    boo = false;
                    break;
                }
            }
            if(boo){
                $.data(target, "datagrid").options.backfillData.push(node);
            }
        },
        onUnSelect: function (target,node) {
            for(var i = 0; i < $.data(target, "datagrid").options.backfillData.length; i++){
                if($.data(target, "datagrid").options.backfillData[i].mid == node.mid){
                    $.data(target, "datagrid").options.backfillData.splice(i,1);
                    break;
                }
            }
        },
        onLoad: function (options,data) {
            var backfillData = options.backfillData;
            for(var i = 0; i < backfillData.length; i++){
                for(var j = 0; j < data.length; j++){
                    if(backfillData[i].mid == data[j].mid){
                        data[j].checked = true;
                        break;
                    }
                }
            }
            return data;
        }
    };


    function init(target, options) {//target 为调用datagrid 的table
        // if (!$().dataTable) {
        //     return;
        // }
        // 生成序号
        buildIndex(target, options);
        // 生成复选框
        buildCheckbox(target, options);
        // 构造dataTable
        var dataTable = $(target).DataTable(options.dataTable);
        bindCheckAll($(target));
        bindCheck($(target));
        bindSelect($(target));
        editRow($(target));//小曼加的行内编辑方法
        $.data(target, 'datagrid', {
            options: options,
            dataTable: dataTable,
            selectedRows: [],
            checkedRows: [],
            originalRows: [],
            updatedRows: [],
            insertedRows: [],
            deletedRows: []
        });
        currentDT=dataTable;
    }

    function buildIndex(target, options) {
        if (options.rownumbers) {
            $(target).find("thead>tr").prepend("<th style='text-align: center;width: 40px;padding-left: 0;padding-right: 0;'>");
            options.dataTable.columns.unshift({//在表前面添加序号列 用unshift 在dataTable.columns[{}]的第一列添加
                "title": "序号",
                "data": "index",
                // render: function (data) {
                //     return'<span class="index">'+ data +'</span>';
                // }
            });
        }
    }

    //生成全选框的唯一标识码
    function generateUUID() {
        var d = new Date().getTime();
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    };

    function buildCheckbox(target, options) {
        if (options.checkbox) {
            $(target).find("thead>tr").prepend("<th>");
            if (options.singleSelect) {//单选radio
                options.dataTable.columns.unshift({//在表前面添加checkbox列 用unshift 在dataTable.columns[{}]的第一列添加
                    "data": "",
                    render: function () {
                        return '<label class="mt-radio mt-radio-outline">' +
                            '<input type="radio" name="radio" value="1" />' +
                            '<span></span>' +
                            '</label>';
                    }
                });
            } else {
                options.uuid = generateUUID();
                options.dataTable.columns.unshift({
                    title: '<label class="mt-checkbox  mt-checkbox-outline">\n' +
                    '<input type="checkbox" id="' + options.uuid + '" class="group-checkable"/>\n' +
                    '<span></span>\n' +
                    '</label>',
                    "data": "",
                    render: function (data, type, row, meta) {
                        if(row.checkBoxDisabled){
                            disabledFalse++;
                        }
                        return '<label class="mt-checkbox '+ (row.checkBoxDisabled ? 'mt-checkbox-disabled' : '') + ' mt-checkbox-outline">' +
                            '<input type="checkbox" class="checkboxes" value="1" ' + (row.checkBoxDisabled ? 'disabled="disabled"' : '') + '/>' +
                            '<span></span>' +
                            '</label>';
                    }
                });
                $("body").on("click", "#" + options.uuid, function () {
                    if ($(this).is(":checked")) {
                        $(target).datagrid("selectAll");
                    } else {
                        $(target).datagrid("unselectAll");
                    }
                });
            }
        }
    }

    function bindCheckAll(table) {
        // handle group checkboxes check/uncheck
        $('.group-checkable', table).change(function () {
            var set = table.find('tbody > tr > td:nth-child(1) input[type="checkbox"]');
            var checked = $(this).prop("checked");
            $(set).each(function () {
                $(this).prop("checked", checked);
                $(this).parent().parent().parent().addClass('selected');
            });
        });
    }

    function bindCheck(table) {
        // handle row's checkbox click
        // table.on('click', 'tbody > tr > td:nth-child(1) input', function (e) {
        //     $(this).parent().parent().parent().toggleClass('selected');
        //     $(this).prop("checked", true);
        //     e.stopPropagation();
        // });
    }

    function bindSelect(table) {
        table.on('click', 'tbody > tr > td:nth-child(1) input', function (e) {
            // $(this).parent().parent().parent().toggleClass('selected');
            // $(this).prop("checked", true);
            e.preventDefault();
            e.stopPropagation();
        });
        table.on('click','tbody > tr  a', function (e) {
            // $(this).parent().parent().parent().toggleClass('selected');
            // $(this).prop("checked", true);
            e.preventDefault();
            e.stopPropagation();
        });

        $(table).on('click', 'tbody > tr', function (e) {
            if(!$(this).find('input[type="checkbox"]').prop('disabled')){
            e.stopPropagation();
            var target = $(this).parent().parent();
            if ($.data(target[0], "datagrid").options.singleSelect) {
                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                    $(this).find('td input[type="radio"]').prop("checked", false);
                } else {
                    $('tr.selected td input[type="radio"]', target).prop("checked", false);
                    $('tr.selected', target).removeClass('selected');
                    $(this).addClass('selected');
                    $(this).find('td input[type="radio"]').prop("checked", true);
                }
            } else {
                var dataTable = $(target[0]).data("datagrid").dataTable,
                    select = dataTable.rows('.selected').data(),
                    allSize = dataTable.rows().data();
                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                    $(this).find('td input[type="checkbox"]').prop("checked", false);

                    if($.data(target[0], "datagrid").options.isBackfill){
                        backfill.onUnSelect(target[0],dataTable.rows().data()[$(this).index()]);
                    }
                    if (typeof $.data(target[0], "datagrid").options.onUnSelect == 'function') {
                        $.data(target[0], "datagrid").options.onUnSelect(dataTable.rows().data()[$(this).index()], $(this).index());
                    }
                } else {
                    $(this).addClass('selected');
                    $(this).find('td input[type="checkbox"]').prop("checked", true);
                    if($.data(target[0], "datagrid").options.isBackfill){
                        backfill.onSelect(target[0],dataTable.rows().data()[$(this).index()]);
                    }
                    if (typeof $.data(target[0], "datagrid").options.onSelect == 'function') {
                        $.data(target[0], "datagrid").options.onSelect(dataTable.rows().data()[$(this).index()], $(this).index());
                    }
                }

                //确定表头全选框是否选中
                if(disabledFalse == 0){
                    if (select.length == allSize.length) {
                        $("#" + $.data(target[0], "datagrid").options.uuid).prop("checked", true);
                    } else {
                        $("#" + $.data(target[0], "datagrid").options.uuid).prop("checked", false);
                    }
                }else{
                    if (select.length == disabledFalse) {
                        $("#" + $.data(target[0], "datagrid").options.uuid).prop("checked", true);
                    } else {
                        $("#" + $.data(target[0], "datagrid").options.uuid).prop("checked", false);
                    }
                }

                //e.stopPropagation();
            }
        }
        });
    }

    function editRow(table){
        table.on("click", "tbody .edit-btn", function () {
            var tds;
            if($('body').find('.DTFC_RightBodyWrapper')){//controls栏是固定时 需要拿取下面数据tabel的当前操作行
                tds = $('#table tbody tr').eq($(this).parents("tr").index()).children();//获取点击按钮TD
            }else{
                tds = $(this).parents("tr").children();//获取点击按钮TDS
            }
            $.each(tds, function (i, val) {//循环tds 把td里加 input
                var jqob = $(val);//把td封装成jquery object
                if (i < 1 || jqob.has('a').length) {//第一列和controls列不需要 input
                    return true;
                } //跳过第1项 序号,按钮
                var txt = jqob.text();//td的val
                var put = $("<input type='text'>");//create input
                put.val(txt);//input val
                jqob.html(put);//td put input
            });
            $(this).html("保存");
            $(this).toggleClass("edit-btn");//have edit-btn set save-btn
            $(this).toggleClass("save-btn");//have save-btn set edit-btn
        });
        table.on("click", "tbody .save-btn", function () {
            var row = currentDT.row($(this).parents("tr"));//把操作的row 对应到 dataTables 中的row
            var tds;
            if($('body').find('.DTFC_RightBodyWrapper')){//controls栏是固定时 需要拿取下面数据tabel的当前操作行
                tds = $('#table tbody tr').eq($(this).parents("tr").index()).children();//获取点击按钮TDS
            }else{
                tds = $(this).parents("tr").children();//获取点击按钮TDS
            }
            $.each(tds, function (i, val) {
                var jqob = $(val);
                //把input变为字符串
                if (!jqob.has('button').length) {
                    var txt = jqob.children("input").val();
                    jqob.html(txt);//把操作row 中的 td 改为text
                    currentDT.cell(jqob).data(txt); //修改DataTables对象的数据
                }
            });
            var data = row.data();
            $(this).html("编辑");
            $(this).toggleClass("edit-btn");
            $(this).toggleClass("save-btn");
        });

    }


    $.fn.datagrid = function (options, param) {
        // console.log(this);//this 则是代表调用datagrid 方法的对象
        if (typeof options == 'string') {//options 如果是一个对象 则是初始化dataTables的参数数据,options.dataTable 获取
            return $.fn.datagrid.methods[options](this, param);
        }
        options = options || {};//用户传进来的
        return this.each(function () {
            var state = $.data(this, 'datagrid');//设置在调用的table里
            var opts;//用户设置的和调用的table对象的option的合并
            if (state) {
                opts = $.extend(state.options, options);
                state.options = opts;
            } else {
                opts = $.extend(true, {}, $.fn.datagrid.defaults, options);
                // 如果使用的是静态数据 则用静态数据渲染 否则用 ajax
                if (opts.dataTable.data !== undefined) {
                    if (opts.dataTable.data) {
                        opts.dataTable.data.forEach(function (row, index) {
                            opts.dataTable.data.index = index + 1;
                        });
                    }
                    opts.dataTable.ajax = null;
                    //opts = $.extend(true, {}, $.fn.datagrid.staticDataOption, options);
                } else {
                    opts.dataTable.ajax.url = opts.url || opts.dataTable.url;
                }
            }
            opts.dataTable.target = this;//把调用对象保存在dataTable.target
            if(opts.isClearStorage){
                localStorage.removeItem("DataTables_" + this.id + "_" + location.pathname);
            }
            init(this, opts);
        });
    };


    $.fn.datagrid.methods = {
        options: function (jq) {
            return $.data(jq[0], 'datagrid').options;
        },
        panels: function (jq) {
            return $.data(jq[0], 'datagrid').panels;
        },
        resize: function (jq, param) {
            return jq.each(function () {
                setSize(this, param);
            });
        },
        getSelections: function (jq) {
            if($.data(jq[0], "datagrid").options.isBackfill){
                return $.data(jq[0], "datagrid").options.backfillData;
            } else {
                var dataTable = $(jq[0]).data("datagrid").dataTable;
                return dataTable.rows('.selected').data();
            }
        },
        getSelected: function (jq) {
            var dataTable = $(jq[0]).data("datagrid").dataTable;
            var rows = dataTable.rows('.selected').data();
            if (rows && rows.length > 0) {
                return rows[0];
            }
        },
        getPanel: function (jq, which) {
            return getPanel(jq[0], which);
        },
        getPanelIndex: function (jq, panel) {
            return getPanelIndex(jq[0], panel);
        },
        select: function (jq, which) {
            return jq.each(function () {
                select(this, which);
            });
        },
        getRows: function (jq) {
            var dataTable = $(jq[0]).data("datagrid").dataTable;
            var data = dataTable.rows().data();
            var rows = new Array();
            for (var i = 0; i < data.length; i++) {
                rows.push(data[i]);
            }
            return rows;
        },
        selectAll: function (jq) {
            var dataTable = $(jq[0]).data("datagrid").dataTable;
            var set = $(jq[0]).find('tbody > tr > td:nth-child(1) input[type="checkbox"]:not(:disabled)');
            console.log(set);
            $(set).each(function () {
                $(this).prop("checked", true);
                $(this).parent().parent().parent().addClass('selected');
                if($.data(jq[0], "datagrid").options.isBackfill){
                    backfill.onSelect(jq[0],dataTable.rows().data()[$(this).parent().parent().parent().index()]);
                }
                if (typeof $.data(jq[0], "datagrid").options.onSelect == 'function') {
                    $.data(jq[0], "datagrid").options.onSelect(dataTable.rows().data()[$(this).parent().parent().parent().index()], $(this).parent().parent().parent().index());
                }
            });


        },
        unselectAll: function (jq) {
            var dataTable = $(jq[0]).data("datagrid").dataTable;
            var set = $(jq[0]).find('tbody > tr > td:nth-child(1) input[type="checkbox"]:not(:disabled)');
            console.log(set);
            if($.data(jq[0], "datagrid").options.isBackfill){
                $.data(jq[0], "datagrid").options.backfillData = [];
            }
            $(set).each(function () {
                $(this).prop("checked", false);
                $(this).parent().parent().parent().removeClass('selected');
                // if($.data(jq[0], "datagrid").options.isBackfill){
                //     backfill.onUnSelect(jq[0],dataTable.rows().data()[$(this).parent().parent().parent().index()]);
                // }
                if (typeof $.data(jq[0], "datagrid").options.onUnSelect == 'function') {
                    $.data(jq[0], "datagrid").options.onUnSelect(dataTable.rows().data()[$(this).parent().parent().parent().index()], $(this).parent().parent().parent().index());
                }
            });
   
        },
        unselect: function (jq, which) {
            var dataTable = $(jq[0]).data("datagrid").dataTable;
            dataTable.rows({selected: true}).data();
        },
        add: function (jq, options) {
            return jq.each(function () {
                add(this, options);
            });
        },
        remove: function (jq, which) {
            return jq.each(function () {
                remove(this, which);
            });
        },
        reload: function (jq, which) {
            if (!which) {
                which = 'searchForm';
            }
            var params = $("#" + which).serializeObject();
            var dataTable = $(jq[0]).data("datagrid").dataTable;
            if($(jq[0]).data("datagrid").options.queryParams){
                params = $.extend(params, $(jq[0]).data("datagrid").options.queryParams);
            }
            dataTable.settings()[0].ajax.url = $(jq[0]).data("datagrid").options.url;
            // var settings = $(jq).dataTable().fnSettings();
            if($(jq[0]).data("datagrid").options.isReLoadNowPage){
                params.isReLoadNowPage = $(jq[0]).data("datagrid").options.isReLoadNowPage;
                params.start = dataTable.settings()[0]._iDisplayStart;
            }
            dataTable.settings()[0].ajax.data.queryParams = params;
            dataTable.ajax.reload();
        },
        resetBackfillData: function (jq) {
            $.data(jq[0], "datagrid").options.backfillData = [];
        }
    };

    $.fn.datagrid.parseOptions = function (target) {
        var t = $(target);
        return $.extend({}, $.parser.parseOptions(target, [
            'width', 'height',
            {fit: 'boolean', border: 'boolean', animate: 'boolean', multiple: 'boolean', selected: 'number'}
        ]));
    };

    /****
     * 覆盖调datatable 弹出框显示错误信息
     * @param s
     * @param h
     * @param m
     */
    $.fn.dataTable.ext.errMode = function (s, h, m) {
        console.log("datatable 警告信息:", s, h, m);
    }


    $.fn.datagrid.defaults = {
        control: null,
        checkbox: false,
        rownumbers: true,
        singleSelect: false,
        checkOnSelect: true,
        selectOnCheck: true,
        queryParams:{},
        isBackfill: false,
        backfillData: [],
        isClearStorage: false,
        isReLoadNowPage: true,//是否在查询重新加载时加载当前页
        start: 0,//保存当前页面页码值
        onSelect: function (node, index) {
        },//数据项选中
        onUnSelect: function (node, index) {
        },//数据项取消选中
        onLoad: function (data) {
            return data;
        },//数据项取消选中
        onDrawCallback: function (oSettings){

        },
        dataTable: {
            target: null,
            "dom": "rb<'table-scrollable't><'row'<'col-md-4 col-sm-12'l><'col-md-4 col-sm-12 pull-right'p>>", // datatable layout
            buttons: [
                {extend: 'print', className: 'btn dark btn-outline'},
                {extend: 'copy', className: 'btn red btn-outline'},
                {extend: 'pdf', className: 'btn green btn-outline'},
                {extend: 'excel', className: 'btn yellow btn-ofutline '},
                {extend: 'csv', className: 'btn purple btn-outline '},
                {extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
            ],
            "pageLength": 10, // default records per page
            "lengthMenu": [
                [10, 20, 50, 100],
                [10, 20, 50, 100] // change per page values here
            ],
            "pagingType": "bootstrap_extended", // pagination type(bootstrap, bootstrap_full_number or bootstrap_extended)
            "orderCellsTop": true,
            //"lengthChange": false,
            "searching": true,
            "ordering": true,
            "autoWidth": true, // disable fixed width and enable fluid table
            "processing": true, // enable/disable display message box on record load
            "serverSide": true, // enable/disable server side ajax loading
            "bStateSave": true,
            "ajax": { // define ajax settings
                "url": "", // ajax URL
                "type": "GET", // request type
                "timeout": 20000,
                "data": function (data) { // add request parameters before submit
                    var queryParams = arguments.callee.queryParams || {};
                    queryParams.draw = data.draw;
                    var url = window.location.href;
                    var isPageReload = url.indexOf("_realod") != -1;
                    if(!queryParams.isReLoadNowPage || queryParams.length >= 0){
                        queryParams.start = data.start;
                    }
                    if(isPageReload){
                        if(url.indexOf("&") == -1){
                            url = url.split("?")[0];
                        } else {
                            url = url.substring(0,url.lastIndexOf("&") + 1);
                        }
                        window.history.pushState({},0,url);

                        queryParams.start = 0;
                        if(arguments[1]){
                            arguments[1]._iDisplayStart = queryParams.start;
                        }
                    }
                    queryParams.length = data.length;
                    if (queryParams.isReLoadNowPage && arguments[1]){
                        var settings = arguments[1];
                        settings._iDisplayStart = queryParams.start;
                        settings._iDisplayLength = queryParams.length;
                    }
                    if (data.order != undefined) {
                        for (var i = 0; i < data.order.length; i++) {
                            if (queryParams.sort == undefined) {
                                queryParams.sort = data.columns[data.order[i].column].data + " " + data.order[i].dir
                            } else {
                                queryParams.sort = data.columns[data.order[i].column].data + " " + data.order[i].dir + ", " + queryParams.sort;
                            }
                        }
                    }
                    return queryParams;
                },
                // Manipulate the data returned from the server
                "dataSrc": function (res) {
                    // if (res.customActionMessage) {
                    //     App.alert({
                    //         type: (res.customActionStatus == 'OK' ? 'success' : 'danger'),
                    //         icon: (res.customActionStatus == 'OK' ? 'check' : 'warning'),
                    //         message: res.customActionMessage,
                    //         container: tableWrapper,
                    //         place: 'prepend'
                    //     });
                    // }
                    //
                    // if (res.customActionStatus) {
                    //     if (tableOptions.resetGroupActionInputOnSuccess) {
                    //         $('.table-group-action-input', tableWrapper).val("");
                    //     }
                    // }
                    //
                    // if ($('.group-checkable', table).size() === 1) {
                    //     $('.group-checkable', table).attr("checked", false);
                    // }
                    //
                    // if (tableOptions.onSuccess) {
                    //     tableOptions.onSuccess.call(undefined, the, res);
                    // }
                    App.unblockUI(tableContainer);
                    // 添加序号
                    if (res.rows) {
                        res.rows.forEach(function (row, index) {
                            row.index = index + 1;
                        })
                    }
                    return res.rows;
                },
                "error": function () { // handle general connection errors
                    // if (tableOptions.onError) {
                    //     tableOptions.onError.call(undefined, the);
                    // }
                    //
                    // App.alert({
                    //     type: 'danger',
                    //     icon: 'warning',
                    //     message: tableOptions.dataTable.language.metronicAjaxRequestGeneralError,
                    //     container: tableWrapper,
                    //     place: 'prepend'
                    // });
                    //
                    // App.unblockUI(tableContainer);
                }
            },
            "fnCookieCallback": function (sName, oData, sExpires, sPath) {
                debugger;
            },
            "drawCallback": function (oSettings) { // run some code on table redraw
                var dataTable = $(oSettings.oInit.target).data("datagrid").dataTable;
                var data = dataTable.rows().data();
                if($.data(oSettings.oInit.target, "datagrid").options.isBackfill){
                    data = backfill.onLoad($.data(oSettings.oInit.target, "datagrid").options, data);
                }
                if (typeof $.data(oSettings.oInit.target, "datagrid").options.onLoad == 'function') {
                    var result = $.data(oSettings.oInit.target, "datagrid").options.onLoad(data);
                    if (result && result.length > 0) {
                        data = result;
                    }
                }

                var set = $(oSettings.oInit.target).find('tbody > tr > td:nth-child(1) input[type="checkbox"]');
                for (var i = 0; i < data.length; i++) {
                    if (data[i]["checked"] && data[i]["checked"] == true) {
                        dataTable.rows(':eq(' + i + ')', {page: 'current'}).select();
                        $(set[i]).prop("checked", true);
                        $(set[i]).parent().parent().parent().addClass('selected');

                    }
                }
                var select = dataTable.rows('.selected').data(),
                    allSize = dataTable.rows().data();
                if (select.length == allSize.length) {
                    $("#" + $.data(oSettings.oInit.target, "datagrid").options.uuid).prop("checked", true);
                } else {
                    $("#" + $.data(oSettings.oInit.target, "datagrid").options.uuid).prop("checked", false);
                }
                if (typeof $.data(oSettings.oInit.target, "datagrid").options.onDrawCallback == 'function') {
                    $.data(oSettings.oInit.target, "datagrid").options.onDrawCallback(oSettings);
                }
            },
            ajaxParams: {},
            // scrollY:        300,
            // deferRender:    true,
            // scroller:       true,
            // scrollX:        true,
            // scrollCollapse: true,
        }
    };

    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    }
})(jQuery);
